﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace Inspired.Euler
{
    public static class Problem035
    {
        public static long Solve()
        {
            var x = "1234".ToCharArray().Permute();

            // http://en.wikipedia.org/wiki/Permutable_prime

            return 
            Enumerable.Range(2, 1000000)
                .Where(i => i.IsPrime())
                //.Where(i => i.ToString().ToCharArray()
                //             .Permute().All(p => Convert.ToInt32(new string(p.ToArray())).IsPrime()))

                .Where(i => i.Circular().All(p => p.IsPrime()))
                
                .Count();
                //.ToArray().Aggregate("", (seed, item) => seed += item.ToString() + ", ")
                //.DisplayAndPause();

        }

        public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> list)
        {
            if (list.Count() <= 1)
                return new List<IEnumerable<T>> { list };

            return list.Select((a, i1) => Permute(list.Where((b, i2) => i2 != i1)).Select(b => (new List<T> { a }).Union(b)))
                       .SelectMany(c => c);
        }

        static IEnumerable<int> Circular(this int number)
        {
            int circ = 0;
            List<char> digits = number.ToString().ToCharArray().ToList();
            do
            {
                digits.Add(digits[0]);
                digits.RemoveAt(0);

                circ = Convert.ToInt32(new string(digits.ToArray()));

                yield return circ;
            } while (circ != number);
        
        }
    }
}
